{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Images and pixels with SimpleITK from R"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The R notebooks follow the general structure of the python equivalents.\n",
    "\n",
    "A few comments to get started:\n",
    "* R will display a variable when you type the name. If the variable is a SimpleITK image then, by default, R/SimpleITK will attempt to display it with ImageJ. This isn't much good for notebooks or knitted documents, so the \"show\" method has been replaced by a function using internal R graphics. This isn't necessary for interactive sessions.\n",
    "* The documentation doesn't exist in the R package yet - be prepared to do some detective work.\n",
    "* C++ enumerated types are wrapped using strings, rather than integers.\n",
    "* Error messages are can be very cryptic - it helps to get familiar with the R way of querying methods and objects.\n",
    "* The object oriented style used by swig is one of the less common ones used in R packages.\n",
    "* C++ vectors are automatically converted to R vectors.\n",
    "\n",
    "Let's start by creating an image and accessing information about it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Load the SimpleITK library\n",
    "library(SimpleITK)\n",
    "\n",
    "imA = Image(256, 128, 64, \"sitkInt16\")\n",
    "imB = SimpleITK::Image(64, 64, \"sitkFloat32\")\n",
    "imC = Image(c(32, 32), \"sitkUInt32\")\n",
    "imRGB = Image(c(128,128), \"sitkVectorUInt8\", 3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We've created 3 different (empty) images using slightly differing syntax to specify the dimensions. We've also specified the pixel type. The range of available pixel types is:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "getAnywhere(\".__E___itk__simple__PixelIDValueEnum\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It isn't usually necessary to access the enumeration classes directly, but it can be handy to know how when debugging."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Lets start querying the images we've created. The `$` operator is used to access object methods:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "imA$GetSize()\n",
    "imC$GetSpacing()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can change the spacing (voxel size):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "imC$SetSpacing(c(2, 0.25))\n",
    "imC$GetSpacing()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "There are shortcuts for accessing a single dimension:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "imC$GetWidth()\n",
    "imA$GetHeight()\n",
    "imA$GetDepth()\n",
    "imC$GetDepth()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The depth refers to the z dimension. A colour or vector image has an additional \"dimension\":"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "imRGB$GetNumberOfComponentsPerPixel()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The list of available methods can be retrieved using the following. There are many functions for accessing pixels in a type dependent way, which don't need to be accessed directly.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "getMethod('$', class(imA))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Array notation for images"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "R, like python and MATLAB, has a flexible notation for accessing elements of arrays. SimpleITK adopts the same notation for accessing pixels (or sub images, which will be covered in a subsequent notebook). First, lets get set up so that we can display an image in the notebook."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# override show function\n",
    "# The example below will respect image voxel sizes\n",
    "## This is a hack to allow global setting of the displayed image width\n",
    "Dwidth <- grid::unit(10, \"cm\")\n",
    "\n",
    "setMethod('show', '_p_itk__simple__Image',\n",
    "         function(object)\n",
    "        {\n",
    "              a <- t(as.array(object))\n",
    "              rg <- range(a)\n",
    "              A <- (a-rg[1])/(rg[2]-rg[1])\n",
    "              dd <- dim(a)\n",
    "              sp <- object$GetSpacing()\n",
    "              sz <- object$GetSize()\n",
    "              worlddim <- sp*sz\n",
    "              worlddim <- worlddim/worlddim[1]\n",
    "              W <- Dwidth\n",
    "              H <- Dwidth * worlddim[2]\n",
    "              grid::grid.raster(A,default.units=\"mm\", width=W, height=H)\n",
    "        }\n",
    "\n",
    "\n",
    "          )\n",
    "options(repr.plot.height = 5, repr.plot.width=5)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Typing the name of an image variable will now result in the image being displayed using an R graphics device. Lets load up an image from the package and test:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we source the code to allow us to fetch images used in examples. This code will download the images if they aren't already on the system."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "source(\"downloaddata.R\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "cthead <- ReadImage(fetch_data(\"cthead1.png\"))\n",
    "cthead"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we will check the value of a single pixel:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "cthead[146, 45]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Pixel access order and conversion to arrays\n",
    "\n",
    "The rule for index ordering in R/SimpleITK is most rapidly changing index first. For images this is x (horizontal), then y (vertical), then z. For R arrays this is row, then column. The conversion between images and arrays maintains the ordering of speed of index change, so the most rapidly changing index is always the first element: \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "imA$GetSize()\n",
    "\n",
    "imA.arr <- as.array(imA)\n",
    "dim(imA.arr)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The array and image dimensions are the same, however if they are displayed they are likely to appear different as R interprets the first index as rows. Also note that traditional graphing tools are likely to interpret vertical direction differently: For example, lets plot the cthead image - the result is flipped vertically, because the graph origin is bottom left, and rows and columns are swapped. The show method we use in this notebook has a transpose operation to reverse the row/column swap."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "image(as.array(cthead))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "R",
   "language": "R",
   "name": "ir"
  },
  "language_info": {
   "codemirror_mode": "r",
   "file_extension": ".r",
   "mimetype": "text/x-r-source",
   "name": "R",
   "pygments_lexer": "r",
   "version": "3.2.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
